package com.solution.admin.customer.filter;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.solution.admin.customer.entity.CustomerVisitLogEntity;
import com.solution.admin.customer.service.CustomerVisitLogService;
import com.solution.admin.product.entity.ProductEntity;
import com.solution.admin.product.service.ProductService;
import com.solution.common.entity.UserPrincipal;

/**
 * 拦截客户访问系统页面，记录访问日志
 * @author zhaiugo
 */
public class CustomerVisitLogFilter implements Filter {
	private static final Logger logger = LoggerFactory.getLogger(CustomerVisitLogFilter.class);

	/**
	 * 注册访问日志业务层组件
	 */
	@Autowired
	private CustomerVisitLogService customerVisitLogService;
	
	/**
	 * 拦截查询商品
	 */
	@Autowired
	private ProductService productService;

	/**
	 * 需要拦截的url地址
	 */
	private static final Map<String, String> urlsMap = new HashMap<String, String>();
	
	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		// 完整地址
		String fullUrl = httpServletRequest.getRequestURL().toString();
		logger.debug("用户正在访问地址：" + fullUrl);
		// 请求路径
		String servletPath = httpServletRequest.getServletPath();
		servletPath = servletPath.substring(0, servletPath.indexOf("?") == -1 ? servletPath.length() : servletPath.indexOf("?"));
		logger.debug("剔除queryString后的地址" + servletPath);
		// 请求域名(判断请求终端)
		String hostName = httpServletRequest.getServerName();
		String terminalType = "pc";
		if(hostName.startsWith("wx.")){
			terminalType = "wx";
		}
		if(urlsMap.containsKey(servletPath)){
			// 查询当前访问客户ID
			Subject currentUser = SecurityUtils.getSubject();
			if(currentUser.isAuthenticated()){
				UserPrincipal user = (UserPrincipal)currentUser.getPrincipal();
				if(user.getCustomer() != null){
					CustomerVisitLogEntity visitLog = new CustomerVisitLogEntity();
					visitLog.setCustomerId(user.getCustomer().getId().longValue());
					visitLog.setTerminalType(terminalType);
					if("/wx/product/detail".equals(servletPath) || "/pc/product/detail".equals(servletPath)){
						String productId = request.getParameter("productId");
						ProductEntity product = productService.getProductById(Long.parseLong(productId));
						String content = urlsMap.get(servletPath).replace("?", product.getProductName());
						visitLog.setVisitContent(content);
					}else{
						visitLog.setVisitContent(urlsMap.get(servletPath));
					}
					visitLog.setVisitUrl(fullUrl);
					visitLog.setVisitTime(new Date());
					customerVisitLogService.saveCustomerVisitLog(visitLog);
				}
			}
		}
        chain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		urlsMap.put("/wx/index", "微信端登录");
		//urlsMap.put("/wx/product/search", "搜索了商品列表");
		urlsMap.put("/wx/product/detail", "查看了商品【?】");
		//urlsMap.put("/wx/product/price/search", "查看了报价单");
		urlsMap.put("/pc/index", "PC端登录");
		//urlsMap.put("/pc/product/search", "搜索了商品列表");
		urlsMap.put("/pc/product/detail", "查看了商品【?】");
		//urlsMap.put("/pc/my/quotation ", "查看了报价单");
	}
}
